package com.atguigu.mybatisplus.web;

import com.atguigu.mybatisplus.entity.User;
import com.atguigu.mybatisplus.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;

/**
 * @Author: MI
 * @Date: 2021/8/29/16:41
 * @Description:
 */
@RestController
@RequestMapping("/test")
public class HelloController {
    @Autowired
    UserService userService;

    @GetMapping("es")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<String> es() {
        try {
            User byId = userService.getById(1);
            System.out.println(byId);
            byId.setAge(byId.getAge() + 1);
            userService.updateById(byId);
            //int i = 1 / 0;
        } catch (Exception e) {
            e.printStackTrace();
            //https://www.cnblogs.com/zt007/p/13355357.html
            // 方法上要加上    @Transactional(rollbackFor = Exception.class)   再配合TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); 才可以
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ResponseEntity.ok("ok");
    }

    @GetMapping("err")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<String> error() {
        // 异步线程是不生效的
        CompletableFuture.runAsync(() -> {
            try {
                System.out.println("HelloController.error");
                userService.ds();
                System.out.println(1 / 0);
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        });
        return ResponseEntity.ok("ok");
    }

    @GetMapping("errs")
    public ResponseEntity<String> errors() {
        try {
            userService.error();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok("ok");
    }

    @GetMapping("es2")
    public ResponseEntity<String> es2() throws Exception {
        userService.ds();
        System.out.println("es-finished");
        CompletableFuture.runAsync(() -> {
            try {

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        return ResponseEntity.ok("ok");
    }

}
